package com.adou.d9.tcp4;

import java.io.*;
import java.net.Socket;

public class ServerReaderThread extends Thread{
    private Socket socket;

    public ServerReaderThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            final DataInputStream dis = new DataInputStream(is);
            while(true) {
                try {
                    String msg = dis.readUTF();
                    System.out.println(msg);

                    // C 把消息分发给全部客户端
                    sendMsgToAll(msg);

                } catch (IOException e) {
                    System.out.println("有人下限了" + socket.getRemoteSocketAddress());
                    Server.onlineSockets.remove(socket);

                    dis.close();
                    socket.close();
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendMsgToAll(String msg) throws IOException {
        // 发送给所有在线
        for (Socket onlineSocket : Server.onlineSockets) {
            OutputStream os = onlineSocket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(msg);
            dos.flush();
        }

    }
}
